#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

static int stack[5];
static int stack_count = 0;

static pthread_t producer_id;
static pthread_t consumer_id1;
static pthread_t consumer_id2;

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t empty = PTHREAD_COND_INITIALIZER;

// 生产者，将数据放入stack
void *producer(void *argv)
{
    while (1)
    {
        // 加锁，独占整个stack
        pthread_mutex_lock(&lock);
        if (stack_count >= 5)
        {
            // 等待消费者消费
            pthread_cond_wait(&full, &lock);
        }

        stack[stack_count++] = rand();
        pthread_cond_signal(&empty);
        pthread_mutex_unlock(&lock);
    }
}

// 消费者，将数据从stack中取出
void *consumer(void *argv)
{
    while (1)
    {
        // 加锁，准备消费
        pthread_mutex_lock(&lock);
        if (stack_count <= 0)
        {
            // 等待生产者生产
            pthread_cond_wait(&empty, &lock);
        }

        printf("从stack中取出%d\n", stack[--stack_count]);
        pthread_cond_signal(&full);
        pthread_mutex_unlock(&lock);
    }
}

int main(int argc, char const *argv[])
{
    pthread_create(&producer_id, NULL, producer, NULL);
    pthread_create(&consumer_id1, NULL, consumer, NULL);
    pthread_create(&consumer_id2, NULL, consumer, NULL);

    pthread_join(producer_id, NULL);
    pthread_join(consumer_id1, NULL);
    pthread_join(consumer_id2, NULL);
    return 0;
}
